﻿CREATE Procedure s_VerItem_Copy
(	@ID int,
	@ParentID int = NULL,
	@AfterID int = NULL,
	@MenuID int = NULL,
	@Move bit = 0
)As

IF @ParentID IS NULL AND @AfterID IS NULL BEGIN
	RAISERROR('Parent or Predecessor must be specified',16,1)
	RETURN
END

IF @ParentID = 0 AND ISNULL(@AfterID,0) = 0 AND ISNULL(@MenuID,0) = 0 BEGIN
	RAISERROR('MenuID must be specified when copying to root',16,1)
	RETURN
END

DECLARE @Pos int

IF ISNULL(@AfterID,0) > 0 
	SELECT @Pos = Pos+1,@ParentID = ParentID,@MenuID = MenuID FROM t_Verification WHERE ID = @AfterID
ELSE
	SELECT @Pos = 0,@MenuID = MenuID FROM t_Verification WHERE ID = @ParentID

IF @Move = 0 BEGIN -- Copy item/tree

	INSERT INTO t_Verification
	SELECT ISNULL(@ParentID,ParentID),Lable,Description,DescToBroker,
				ISNULL(@Pos,Pos+1), PageID,ImageTypeID,DefaultValue,
				ISNULL(@MenuID,MenuID),IsSmart,IsParent
	FROM  t_Verification WHERE ID = @ID

	SET @ParentID = IDENT_CURRENT('t_Verification')

	DECLARE cur cursor LOCAL FAST_FORWARD FOR
	SELECT ID FROM t_Verification WHERE ParentID = @ID ORDER BY Pos
	OPEN cur
	FETCH NEXT FROM cur INTO @ID
	WHILE @@FETCH_STATUS = 0 BEGIN
		EXEC s_VerItem_Copy @ID,@ParentID,NULL,@MenuID
		IF @@ERROR <> 0 BREAK
		FETCH NEXT FROM cur INTO @ID
	END
	CLOSE cur
	DEALLOCATE cur

END ELSE BEGIN
	UPDATE t_Verification SET ParentID = @ParentID,Pos = @Pos,MenuID = @MenuID WHERE ID = @ID
	PRINT @ID
	PRINT @ParentID
	--RAISERROR('Move is not supported',16,1)
END

RETURN @ParentID
